#include "MQTTClient.h"
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

using namespace mqtt;

int main() {
  // 创建客户端，使用基础ID "testClient"
  MQTTClient client("testClient");

  // 设置默认消息回调
  client.set_default_callback(
      [](const std::string &topic, const std::string &msg) {
        std::cout << "[默认回调] topic: " << topic << ", payload: " << msg
                  << std::endl;
      });

  // 连接到 broker
  client.connect("192.168.5.11", 1883, "", "", 1, 60);

  // 等待连接成功
  while (!client.isConnected()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }

  std::cout << "✅ 已连接到 Broker\n";

  // 多次订阅主题
  std::vector<std::string> topics = {"topic/1", "topic/2", "topic/3"};
  for (const auto &t : topics) {
    client.subscribe(t, 1,
                     [t](const std::string &topic, const std::string &msg) {
                       std::cout << "[回调] topic: " << topic
                                 << ", payload: " << msg << std::endl;
                     });
  }

  // 多次发布消息
  for (int i = 0; i < 5; ++i) {
    for (const auto &t : topics) {
      std::string payload = "Hello " + std::to_string(i) + " to " + t;
      client.publish(t, payload);
      std::cout << "📤 发布: " << payload << std::endl;
    }
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }

  // 等待接收消息
  std::this_thread::sleep_for(std::chrono::seconds(5));

  client.disconnect();
  std::cout << "⚠️ 已断开客户端\n";

  return 0;
}
